﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Media.Animation;
using System.IO;
using AddressBookModel;
using System.ComponentModel;
using Exceptions;

namespace AppControl
{
    /// <summary>
    /// Interaction logic for ContactsWindow.xaml
    /// </summary>
    public partial class ContactsWindow : Window
    {
        public static ICollectionView GroupedContacts { get; private set; }

        public ContactsWindow()
        {
            InitializeComponent();
            LoadComponents();
        }

        private void LoadComponents()
        {
            Contact.Contacts.Clear();

            if (File.Exists("contacts.txt"))
            {
                try
                {
                    var reader = new StreamReader("contacts.txt");

                    using (reader)
                    {
                        var serializedContacts = reader.ReadToEnd();
                        ContactFactory contacts = new ContactFactory();
                        contacts.CreateContacts(serializedContacts);
                    }
                }
                catch (FileLoadException ex) { MessageBox.Show(ex.Message); }
                catch (IOException ex) { MessageBox.Show(ex.Message); }
            }
            else
            {
                try { File.Create("contacts.txt"); }
                catch (PathTooLongException ex) { MessageBox.Show(ex.Message); }
                catch (DirectoryNotFoundException ex) { MessageBox.Show(ex.Message); }
                catch (UnauthorizedAccessException ex) { MessageBox.Show(ex.Message); }
                catch (IOException ex) { MessageBox.Show(ex.Message); }
            }

            GroupedContacts = new ListCollectionView(Contact.Contacts);
            GroupedContacts.GroupDescriptions.Add(new PropertyGroupDescription("Group"));
            GroupedContacts.SortDescriptions.Add(new SortDescription("Name", ListSortDirection.Ascending));
            preview.ItemsSource = GroupedContacts;
        }

        private void OnContactDeleteClick(object sender, RoutedEventArgs e)
        {
            var index = this.preview.SelectedIndex;

            string messageBoxText = string.Format(@"Do you want to delete{0}this contact?", Environment.NewLine);
            string caption = AddressBook.Title;
            MessageBoxButton messageBoxBtn = MessageBoxButton.YesNo;
            MessageBoxImage messageBoxIcon = MessageBoxImage.Question;
            MessageBoxResult messageBoxResult = MessageBox.Show(messageBoxText, caption, messageBoxBtn, messageBoxIcon);

            switch (messageBoxResult)
            {
                case MessageBoxResult.Yes:
                    string picture = ((GroupedContacts as ListCollectionView).GetItemAt(index) as Contact).Picture;
                    string fileName = System.IO.Path.GetFileName(picture);
                    if (fileName != "BusinessIcon.png" && fileName != "FamilyIcon.png" &&
                        fileName != "FriendIcon.png" && fileName != "OtherIcon.png")
                    {
                        PictureManager.AddPictureForDeletion(picture);
                    }

                    (GroupedContacts as ListCollectionView).RemoveAt(index);
                    preview.Items.Refresh();
                    break;
            }
        }

        private void OnAddPictureClick(object sender, RoutedEventArgs e)
        {
            Microsoft.Win32.OpenFileDialog dialog = new Microsoft.Win32.OpenFileDialog();
            dialog.FileName = "All Picture Files";
            dialog.DefaultExt = ".jpeg";
            dialog.Filter = "All supported graphics|*.jpg;*.jpeg;*.png|" +
                "JPEG (*.jpg;*.jpeg)|*.jpg;*.jpeg|" + "Portable Network Graphic (*.png)|*.png";

            Nullable<bool> result = dialog.ShowDialog();

            if (result == true)
            {
                var index = this.preview.SelectedIndex;
                Contact contact = (Contact)(GroupedContacts as ListCollectionView).GetItemAt(index);

                string picture = contact.Picture;
                string fileName = System.IO.Path.GetFileName(picture);
                if (fileName != "BusinessIcon.png" && fileName != "FamilyIcon.png" &&
                    fileName != "FriendIcon.png" && fileName != "OtherIcon.png" && File.Exists(picture))
                {
                    PictureManager.AddPictureForDeletion(picture);
                }

                string sourceFile = dialog.FileName;
                contact.Picture = PictureManager.ManagePicture(sourceFile);
                (GroupedContacts as ListCollectionView).CommitEdit();
                (GroupedContacts as ListCollectionView).Refresh();
            }
        }

        private void OnAddBtnClick(object sender, RoutedEventArgs e)
        {
            try
            {
                Contact.ValidateContact(this.PersonName.Text, this.Mobile.Text, this.PersonBirthday.Text);

                ContactFactory factory = new ContactFactory();
                Contact newContact;

                if (GroupType.SelectionBoxItem.ToString() == "Family")
                {
                    newContact = factory.CreateFamilyContact(this.PersonName.Text.Trim(), this.Mobile.Text.Trim(),
                       this.PersonEmail.Text.Trim(), this.PersonBirthday.Text.Trim());
                }
                else if (GroupType.SelectionBoxItem.ToString() == "Friends")
                {
                    newContact = factory.CreateFriendContact(this.PersonName.Text.Trim(), this.Mobile.Text.Trim(),
                       this.PersonEmail.Text.Trim(), this.PersonBirthday.Text.Trim());
                }
                else if (GroupType.SelectionBoxItem.ToString() == "Business")
                {
                    newContact = factory.CreateBusinessContact(this.PersonName.Text.Trim(), this.Mobile.Text.Trim(),
                       this.PersonEmail.Text.Trim(), this.PersonBirthday.Text.Trim());
                }
                else
                {
                    newContact = factory.CreateOtherContact(this.PersonName.Text.Trim(), this.Mobile.Text.Trim(),
                       this.PersonEmail.Text.Trim(), this.PersonBirthday.Text.Trim());
                }

                (GroupedContacts as ListCollectionView).AddNewItem(newContact);
                (GroupedContacts as ListCollectionView).CommitNew();

                this.PersonName.Text = "";
                this.PersonEmail.Text = "";
                this.PersonBirthday.Text = "";
                this.Mobile.Text = "";
            }
            catch (InvalidDateException ex) { MessageBox.Show(ex.Message); }
            catch (InvalidPhoneException ex) { MessageBox.Show(ex.Message); }
            catch (AddressBookException ex) { MessageBox.Show(ex.Message); }
        }

        private void OnContactsWindowClosed(object sender, EventArgs e)
        {
            var writeContacts = new StreamWriter("contacts.txt", false);

            try
            {
                using (writeContacts)
                {
                    foreach (Contact contact in GroupedContacts)
                    {
                        writeContacts.WriteLine(contact.Serialize());
                    }
                }
            }
            catch (PathTooLongException ex) { MessageBox.Show(ex.Message); }
            catch (FileNotFoundException ex) { MessageBox.Show(ex.Message); }
            catch (DirectoryNotFoundException ex) { MessageBox.Show(ex.Message); }
            catch (UnauthorizedAccessException ex) { MessageBox.Show(ex.Message); }
            catch (IOException ex) { MessageBox.Show(ex.Message); }

            PictureManager.SavePictureDeletionList();
        }

        private void OnDelKeyboardKey(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Delete)
            {
                var index = this.preview.SelectedIndex;

                string messageBoxText = string.Format(@"Do you want to delete{0}this contact?", Environment.NewLine);
                string caption = AddressBook.Title;
                MessageBoxButton messageBoxBtn = MessageBoxButton.YesNo;
                MessageBoxImage messageBoxIcon = MessageBoxImage.Question;
                MessageBoxResult messageBoxResult = MessageBox.Show(messageBoxText, caption, messageBoxBtn, messageBoxIcon);

                switch (messageBoxResult)
                {
                    case MessageBoxResult.Yes:
                        string picture = ((GroupedContacts as ListCollectionView).GetItemAt(index) as Contact).Picture;
                        string fileName = System.IO.Path.GetFileName(picture);
                        if (fileName != "BusinessIcon.png" && fileName != "FamilyIcon.png" &&
                            fileName != "FriendIcon.png" && fileName != "OtherIcon.png")
                        {
                            PictureManager.AddPictureForDeletion(picture);
                        }

                        (GroupedContacts as ListCollectionView).RemoveAt(index);
                        preview.Items.Refresh();
                        break;
                }
            }
        }

        private void OnContactEditClick(object sender, RoutedEventArgs e)
        {
            var editContact = new EditContactWindow();
            editContact.Owner = this;
            editContact.ShowDialog();
        }

        private void RowDoubleClick(object sender, RoutedEventArgs e)
        {
            var row = (DataGridRow)sender;
            row.DetailsVisibility = row.DetailsVisibility == Visibility.Collapsed ?
                Visibility.Visible : Visibility.Collapsed;
        }

        private void preview_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }

        private void OnSendMailClick(object sender, RoutedEventArgs e)
        {
            var index = this.preview.SelectedIndex;
            Contact contact = (Contact)(GroupedContacts as ListCollectionView).GetItemAt(index);

            if (contact.Email != "")
            {
                // Open the "HKLM\SOFTWARE\Clients\Mail" key.
                Microsoft.Win32.RegistryKey mailKey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Clients\Mail");

                // The default mail application is stored in the default value of that key.
                string defaultMailApp = (string)mailKey.GetValue(null);

                if (defaultMailApp != null && defaultMailApp.Length > 0)
                {
                    string fileName = "mailto:" + contact.Email;
                    System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(fileName));
                }
                else MessageBox.Show("Install/Set default mail client!");
            }
            else
            {
                MessageBox.Show(this, "Enter e-mail in contact form first!");
            }
        }
    }
}
